<?php
namespace App\Http\Controllers\desktop\publics;

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use App\Models\Member;
use Illuminate\Support\Facades\Hash;

class RegisterController extends BaseController {
	
	public function index() {
		if(Auth::check()) {
			return redirect('/cs');
		}
		return view('desktop.publics.register');
	}
	
	public function attempt() {
		$input = Input::all();
		$validation = validator($input, self::$rules, self::$msgs);
		if ($validation->passes()) {
			if($input['cPassword'] != $input['password']) {
				Session::flash('msg', '两次密码输入不一致。');
				return Redirect::back();
			}
			unset($input['cPassword']);
			$input['password'] = Hash::make($input['password']);
			$input['avatar'] = 'avatar.jpg';
			$member = Member::create($input);
			if (Auth::attempt(array(
				'cellphone' => $member->cellphone,
				'password' => $member->password,
			))) {
				return Redirect::to('/cs');
			}
			Session::flash('msg', '登录失败。');
		}
		return Redirect::back()
			->withInput()
			->withErrors($validation);
	}

	public static $rules = array(
		'nickname' => 'required',
		'gender' => 'required',
		'cellphone' => array('required', 'regex:/^0{0,1}(13[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/', 'unique:members'),
		'password' => 'required|between:6,16',
		'email' => 'required|email|unique:members',
	);
	
	public static $msgs = array(
		'nickname.required' => '昵称不能为空。',
		'gender.required' => '性别不能为空。',
		'cellphone.required' => '手机号码不能为空。',
		'cellphone.regex' => '手机号码格式不正确。',
		'cellphone.unique' => '该手机号已经被注册。',
		'password.required' => '请填写您的密码。',
		'password.between' => '密码必须在:min-:max个字符之间。',
		'email.required' => '邮箱不能为空。',
		'email.email' => '邮箱格式不正确。',
		'email.unique' => '该邮箱已被注册。'
	);
}
